﻿using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using SPLinkedInProxy.ProxyCode;
using System.Xml;

namespace SPLinkedIn.SPLinkedInWP
{
    [ToolboxItemAttribute(false)]
    public class SPLinkedInWP : WebPart
    {
        bool bGetAccessToken = false;

        Label lblErrorMessages = new Label();
        Label lblLoginURL = new Label();
        Label lblProfileStatus = new Label();

        Button btnCreateAuthorization = new Button();
        Button btnGetAccessToken = new Button();
        Button btnSendStatusUpdate = new Button();
        Button btnRequestProfile = new Button();

        TextBox txtProfileStatus = new TextBox();

        public string txtRequestToken { get; set; }
        public string txtTokenSecret { get; set; }
        public string txtoAuth_token { get; set; }
        public string txtoAuth_verifier { get; set; }
        public string txtAccessToken { get; set; }
        public string txtAccessTokenSecret { get; set; }
        public string txtApiResponse { get; set; }
        public string txtCommandName { get; set; }
        public string txtErrorMsg { get; set; }

        public string hypAuthToken { get; set; }

        SPListOps spl = new SPListOps();

        public SPLinkedInWP()
        {
        }

        protected override void OnLoad(EventArgs e)
        {
            this.txtoAuth_token = Page.Request.QueryString["oauth_token"];
            this.txtoAuth_verifier = Page.Request.QueryString["oauth_verifier"];
            if (txtoAuth_token != null && txtoAuth_verifier != null)
            {
                txtRequestToken = spl.SPListGetItemValue("requestToken");
                txtTokenSecret = spl.SPListGetItemValue("requestTokenSecret");
                hypAuthToken = spl.SPListGetItemValue("oauthLink");

                spl.SPListAddItems("oauth_token", txtoAuth_token);
                spl.SPListAddItems("oauth_verifier", txtoAuth_verifier);
                
                btnGetAccessToken.Visible = true;

                if (bGetAccessToken == false)
                {
                    lblErrorMessages.Text = "Authorization Successfuly. We now need to retrieve the Access Token. Click the button below";
                    lblProfileStatus.Visible = false;
                    txtProfileStatus.Visible = false;
                    btnSendStatusUpdate.Visible = false;
                    btnRequestProfile.Visible = false;
                }

            }            
            base.OnLoad(e);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            btnCreateAuthorization.Click += new EventHandler(btnCreateAuthorization_Click);
            btnGetAccessToken.Click += new EventHandler(btnGetAccessToken_Click);
            btnSendStatusUpdate.Click += new EventHandler(btnSendStatusUpdate_Click);
            btnRequestProfile.Click += new EventHandler(btnRequestProfile_Click);
        }

        void btnRequestProfile_Click(object sender, EventArgs e)
        {
            try
            {
                this.txtAccessToken = spl.SPListGetItemValue("accessToken");
                this.txtAccessTokenSecret = spl.SPListGetItemValue("accessTokenSecret");

                SPLinkedInProxyArgs proxyArgs = new SPLinkedInProxyArgs("RequestProfile",
                                                this.txtRequestToken,
                                                this.txtTokenSecret,
                                                this.txtoAuth_token,
                                                this.txtoAuth_verifier,
                                                this.txtAccessToken,
                                                this.txtAccessTokenSecret,
                                                this.txtApiResponse,
                                                this.hypAuthToken);

                proxyArgs.txtProfileStatus = txtProfileStatus.Text;

                SPLinkedInProxy.ProxyCode.SPLinkedInProxyArgs spproxyArgs =
                    (SPLinkedInProxy.ProxyCode.SPLinkedInProxyArgs)SPUtility.ExecuteRegisteredProxyOperation(
                    "SPLinkedInProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c5b2735a354d31ca",
                    "SPLinkedInProxy.ProxyCode.SPLinkedInProxyOperation",
                    proxyArgs);

                if (spproxyArgs.txtErrorMsg != null)
                    lblErrorMessages.Text = "Error: " + spproxyArgs.txtErrorMsg.ToString();
                else
                {
                    this.txtApiResponse = spproxyArgs.txtApiResponse;

                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(this.txtApiResponse);

                    XmlNodeList fname = doc.GetElementsByTagName("first-name");
                    XmlNodeList lname = doc.GetElementsByTagName("last-name");
                    XmlNodeList headline = doc.GetElementsByTagName("headline");
                    XmlNodeList currentstatus = doc.GetElementsByTagName("current-status");
                    XmlNodeList summary = doc.GetElementsByTagName("summary");

                    lblLoginURL.Text = "<TABLE border=\"1\" width=\"100%\">";
                    lblLoginURL.Text += "<TR>";
                    lblLoginURL.Text += "<TD align=\"left\"><font color=\"black\">First Name: </td><td>" + fname[0].InnerText + "</font></td>";
                    lblLoginURL.Text += "</TR>";
                    lblLoginURL.Text += "<TR><TD align=\"left\"><font color=\"black\">Last Name: </td><td>" + lname[0].InnerText + "</font></td></TR>";
                    lblLoginURL.Text += "<TR><TD align=\"left\"><font color=\"black\">Headline: </td><td>" + headline[0].InnerText + "</font></td></TR>";
                    lblLoginURL.Text += "<TR><TD align=\"left\"><font color=\"black\">Current Status: </td><td>" + currentstatus[0].InnerText + "</font></td></TR>";
                    lblLoginURL.Text += "<TR><TD alignt =\"left\" valign=\"top\"><font color=\"black\">Summary: </td><td>" + summary[0].InnerText + "</font></td></TR>";
                    lblLoginURL.Text += "</TABLE>";


                    //lblLoginURL.Text = this.txtApiResponse;

                    lblErrorMessages.Text = "";

                    lblProfileStatus.Visible = true;
                    txtProfileStatus.Visible = true;
                    btnSendStatusUpdate.Visible = true;
                    btnRequestProfile.Visible = true;

                    btnGetAccessToken.Visible = false;
                    bGetAccessToken = true;
                }
            }
            catch (Exception x)
            {
                lblErrorMessages.Text = x.Message;
            }
        }

        void btnSendStatusUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                this.txtAccessToken = spl.SPListGetItemValue("accessToken");
                this.txtAccessTokenSecret = spl.SPListGetItemValue("accessTokenSecret");

                SPLinkedInProxyArgs proxyArgs = new SPLinkedInProxyArgs("SendStatusUpdate",
                                                this.txtRequestToken,
                                                this.txtTokenSecret,
                                                this.txtoAuth_token,
                                                this.txtoAuth_verifier,
                                                this.txtAccessToken,
                                                this.txtAccessTokenSecret,
                                                this.txtApiResponse,
                                                this.hypAuthToken);

                proxyArgs.txtProfileStatus = txtProfileStatus.Text;

                SPLinkedInProxy.ProxyCode.SPLinkedInProxyArgs spproxyArgs =
                    (SPLinkedInProxy.ProxyCode.SPLinkedInProxyArgs)SPUtility.ExecuteRegisteredProxyOperation(
                    "SPLinkedInProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c5b2735a354d31ca",
                    "SPLinkedInProxy.ProxyCode.SPLinkedInProxyOperation",
                    proxyArgs);

                if (spproxyArgs.txtErrorMsg != null)
                    lblErrorMessages.Text = "Error: " + spproxyArgs.txtErrorMsg.ToString();
                else
                {
                    this.txtApiResponse = spproxyArgs.txtApiResponse;
                    lblLoginURL.Text = this.txtApiResponse;

                    lblErrorMessages.Text = "";

                    lblProfileStatus.Visible = true;
                    txtProfileStatus.Visible = true;
                    btnSendStatusUpdate.Visible = true;
                    btnRequestProfile.Visible = true;

                    btnGetAccessToken.Visible = false;
                    bGetAccessToken = true;
                }
            }
            catch (Exception x)
            {
                lblErrorMessages.Text = x.Message;
            }

        }

        void btnGetAccessToken_Click(object sender, EventArgs e)
        {
            try
            {
                SPLinkedInProxyArgs proxyArgs = new SPLinkedInProxyArgs("GetAccessToken",
                    this.txtRequestToken,
                    this.txtTokenSecret,
                    this.txtoAuth_token,
                    this.txtoAuth_verifier,
                    this.txtAccessToken,
                    this.txtAccessTokenSecret,
                    this.txtApiResponse,
                    this.hypAuthToken);

                SPLinkedInProxy.ProxyCode.SPLinkedInProxyArgs spproxyArgs =
                    (SPLinkedInProxy.ProxyCode.SPLinkedInProxyArgs)SPUtility.ExecuteRegisteredProxyOperation(
                    "SPLinkedInProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c5b2735a354d31ca",
                    "SPLinkedInProxy.ProxyCode.SPLinkedInProxyOperation",
                    proxyArgs);

                if (spproxyArgs.txtErrorMsg != null)
                    lblErrorMessages.Text = "Error: " + spproxyArgs.txtErrorMsg.ToString();
                else
                {
                    this.txtRequestToken = spproxyArgs.txtRequestToken;
                    this.txtTokenSecret = spproxyArgs.txtTokenSecret;
                    this.hypAuthToken = spproxyArgs.hypAuthToken;

                    this.txtAccessToken = spproxyArgs.txtRequestToken;
                    this.txtAccessTokenSecret = spproxyArgs.txtTokenSecret;

                    spl.SPListAddItems("accessToken", spproxyArgs.txtAccessToken);
                    spl.SPListAddItems("accessTokenSecret", spproxyArgs.txtAccessTokenSecret);


                    lblErrorMessages.Text = "";
                    btnCreateAuthorization.Visible = false;
                    btnGetAccessToken.Visible = false;

                    lblProfileStatus.Visible = true;
                    txtProfileStatus.Visible = true;

                    btnSendStatusUpdate.Visible = true;
                    btnRequestProfile.Visible = true;


                    lblLoginURL.Text = "Retrieved Access Token: " + this.txtAccessToken;
                    lblLoginURL.Text += "\n You may now perform API activities.";

                    bGetAccessToken = true;
                }
            }
            catch (Exception x)
            {
                lblErrorMessages.Text = x.Message;
            }
        }

        protected override void CreateChildControls()
        {
            btnCreateAuthorization.Text = "Create Authorization";
            Controls.Add(btnCreateAuthorization);

            btnGetAccessToken.Text = "Get Access Token";
            if (txtoAuth_token == null && txtoAuth_verifier == null)
                btnGetAccessToken.Visible = false;
            Controls.Add(btnGetAccessToken);

            if (txtoAuth_token == null && txtoAuth_verifier == null)
            {
                lblProfileStatus.Text = "Enter your current status here: ";
                lblProfileStatus.Visible = false;
                txtProfileStatus.Visible = false;
                btnSendStatusUpdate.Visible = false;
                btnRequestProfile.Visible = false;
            }

            btnRequestProfile.Text = "Request Profile";
            btnSendStatusUpdate.Text = "Send Status Update";
            Controls.Add(lblProfileStatus);
            Controls.Add(txtProfileStatus);
            Controls.Add(btnSendStatusUpdate);
            Controls.Add(btnRequestProfile);

            base.CreateChildControls();
        }


        void btnCreateAuthorization_Click(object sender, EventArgs e)
        {           
            try
            {
                spl.SPListClearListItems();

                SPLinkedInProxyArgs proxyArgs = new SPLinkedInProxyArgs("Authorize");

                SPLinkedInProxy.ProxyCode.SPLinkedInProxyArgs spproxyArgs  = 
                    (SPLinkedInProxy.ProxyCode.SPLinkedInProxyArgs)SPUtility.ExecuteRegisteredProxyOperation(
                    "SPLinkedInProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c5b2735a354d31ca",
                    "SPLinkedInProxy.ProxyCode.SPLinkedInProxyOperation",
                    proxyArgs);

                if (spproxyArgs.txtErrorMsg != null)
                    lblErrorMessages.Text = "Error: " + spproxyArgs.txtErrorMsg.ToString();
                else
                {
                    this.txtRequestToken = spproxyArgs.txtRequestToken;
                    this.txtTokenSecret = spproxyArgs.txtTokenSecret;
                    this.hypAuthToken = spproxyArgs.hypAuthToken;

                    spl.SPListAddItems("requestToken", spproxyArgs.txtRequestToken);
                    spl.SPListAddItems("requestTokenSecret", spproxyArgs.txtTokenSecret);
                    spl.SPListAddItems("oauthLink", spproxyArgs.hypAuthToken);

                    lblLoginURL.Text = "Please " + "<a href=\"" + hypAuthToken.ToString() + "\">" + "Click Here </a> to SignIn to LinkedIn";
                }
            }
            catch (Exception x)
            {
                lblErrorMessages.Text = x.Message;
            }
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.WriteLine("<BR>");
            writer.WriteLine("<BR>");
            writer.WriteLine("<TABLE width=\"100%\"><TR><TD align=\"center\">");
            writer.Write("SharePoint 2010 - LinkedIn Integration Web Part");
            writer.WriteLine("</TD></TR>");
            writer.WriteLine("<TR><TD align=\"center\">");
            writer.Write("Version 1.0");
            writer.WriteLine("</TD></TR></TABLE>");
            writer.WriteLine("<BR>");

            btnCreateAuthorization.RenderControl(writer);
            writer.WriteLine("<BR>");
            lblErrorMessages.RenderControl(writer);
            writer.WriteLine("<BR>");
            lblLoginURL.RenderControl(writer);
            writer.WriteLine("<BR>");
            btnGetAccessToken.RenderControl(writer);
            writer.WriteLine("<BR>");
            lblProfileStatus.RenderControl(writer);
            txtProfileStatus.RenderControl(writer);
            btnSendStatusUpdate.RenderControl(writer);
            writer.WriteLine("<BR>");
            writer.WriteLine("<BR>");
            if(bGetAccessToken == true)
                writer.WriteLine("OR");

            writer.WriteLine("<BR>");
            writer.WriteLine("<BR>");
            btnRequestProfile.RenderControl(writer);
            writer.WriteLine("<BR>");

        }
    }
}
